package com.joolun.app;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.joolun.common.constant.Constants;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.core.domain.model.LoginBody;
import com.joolun.common.core.domain.model.LoginUser;
import com.joolun.common.exception.CustomException;
import com.joolun.common.utils.ServletUtils;
import com.joolun.framework.web.service.SysLoginService;
import com.joolun.framework.web.service.TokenService;
import com.joolun.system.domain.vo.AppRegReq;
import com.joolun.system.domain.vo.AppVerCodeReq;
import com.joolun.system.domain.vo.ChangePasswordReq;
import com.joolun.system.service.IAppService;
import com.joolun.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 处理app请求
 *
 * @author yto_xx
 * @DATE 2021-02-23 09:10
 */
@RestController
@RequestMapping("/app")
public class AppController extends BaseController {

    @Autowired
    ISysUserService userService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IAppService appService;

    @ApiOperation("注册发送验证码")
    @PostMapping("/regVerCode")
    public AjaxResult regVerCode(@RequestBody AppVerCodeReq user) {
        AjaxResult ajax = AjaxResult.success();
        try {
            appService.getVerificationCode(user.getPhonenumber());
        } catch (Exception e) {
            ajax = AjaxResult.error("获取验证码异常");
        }
        return ajax;
    }

    @ApiOperation("发送验证码")
    @PostMapping("/verCode")
    public AjaxResult sendMsgCode() {
        AjaxResult ajax = AjaxResult.success();
        try {
            LoginUser logUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (logUser == null) {
                throw new CustomException("非登录状态，请先登录");
            } else {
                // dapp 注册时没有手机号，第一次录入手机号时，系统是空，取用户输入手机号发送验证码；后面都用系统保存的手机号来发送；如果手机丢失需要联系管理员修改；
//                appService.getVerificationCode(logUser.getUser().getPhonenumber().isEmpty() ? user.getPhonenumber() : logUser.getUser().getPhonenumber());
                // 正常注册后登录的用注册时的手机号
                appService.getVerificationCode(logUser.getUser().getPhonenumber());
            }
        } catch (Exception e) {
            ajax = AjaxResult.error("获取验证码异常");
        }

        return ajax;
    }

    //    @ApiOperation("1注册")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody AppRegReq userReq) {
        AjaxResult ajax = AjaxResult.success();
        try {
            userService.insertAppUser(userReq);
        } catch (Exception e) {
            e.printStackTrace();
            ajax = AjaxResult.error(e.getMessage());
        }
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        try {
            if ("admin".equalsIgnoreCase(loginBody.getUsername())) {
                ajax = AjaxResult.error("禁止登录");
                return ajax;
            }
            // 生成令牌
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());

            ajax.put(Constants.TOKEN, token);
        } catch (Exception e) {
            ajax = AjaxResult.error(e.getMessage());
        }
        return ajax;
    }

    @ApiOperation("后台管理员登录验证码")
    @PostMapping("/adminMsgCode")
    public AjaxResult adminMsgCode() {
        AjaxResult ajax = AjaxResult.success();
        try {
            SysUser qry = new SysUser();
            qry.setUserName("admin");
            SysUser user = userService.getAppUser(qry);
            appService.getVerificationCode(user.getPhonenumber());
        } catch (Exception e) {
            ajax = AjaxResult.error(e.getMessage());
        }
        return ajax;
    }


    /**
     * 针对注册时不需要绑定手机的系统，绑定手机号
     *
     * @param user
     * @return 结果
     */
    @ApiOperation("针对注册时不需要绑定手机的系统，绑定手机号")
    @PostMapping("/setPhone")
    public AjaxResult setPhone(@RequestBody SysUser user) {
        AjaxResult ajax = AjaxResult.success();

        try {
            LoginUser logUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (logUser == null) {
                throw new CustomException("非登录状态，请登录后操作");
            }
            SysUser u = logUser.getUser();
            u.setUserId(logUser.getUser().getUserId());
            u.setVerCode(user.getVerCode());
            appService.setPhone(u, user.getPhonenumber());

            u.setPhonenumber(user.getPhonenumber());
            logUser.setUser(u);
            tokenService.setLoginUser(logUser);
        } catch (Exception e) {
            ajax = AjaxResult.error(e.getMessage());
        }
        return ajax;
    }

    /**
     * 修改密码
     * verCode password
     *
     * @param changePasswordReq
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author chenlei
     * @date 2021-2-24 08:53
     */
    @ApiOperation("修改密码")
    @PostMapping("/password")
    public AjaxResult changePassword(@RequestBody ChangePasswordReq changePasswordReq) {
        AjaxResult ajax = AjaxResult.success();
        try {
            SysUser u;
            LoginUser logUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if (logUser == null) {
                SysUser temp = new SysUser();
                temp.setUserName(changePasswordReq.getUserName());
                temp.setPhonenumber(changePasswordReq.getPhonenumber());
                u = userService.getAppUser(temp);
                if (u == null) {
                    throw new CustomException("用户名手机号不匹配");
                }
            } else {
                u = logUser.getUser();
            }
            u.setVerCode(changePasswordReq.getValidCode());
            u.setPassword(changePasswordReq.getPassword());
            appService.changePassword(u);
        } catch (Exception e) {
            ajax = AjaxResult.error(e.getMessage());
        }
        return ajax;
    }


}
